package com.ysucloud.manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.ysucloud.manager.VO.ResultListVO;
import com.ysucloud.manager.converter.ProductFormToProductInfo;
import com.ysucloud.manager.converter.ProductWidFormToProductInfo;
import com.ysucloud.manager.dataobject.ProductInfo;
import com.ysucloud.manager.exception.NullParameterException;
import com.ysucloud.manager.form.ProductForm;
import com.ysucloud.manager.form.ProductWidForm;
import com.ysucloud.manager.server.ProductInfoServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 主要实现业务的增删改查
 *
 * Description: manager
 * Created by 刘翰文 on 2019/6/27 15:53
 */
@RestController
@RequestMapping("/product")
public class ProductInfoController {
    @Autowired
    ProductInfoServer productInfoServer;

    /** 查询 */
    @PostMapping("get")
    public ResultListVO getAll(){
        List<ProductInfo> productInfoList =
                productInfoServer.getAllProduct();

        ResultListVO result = new ResultListVO();

        result.setData(productInfoList);

        return result;
    }

    /** 增加 */
    @PostMapping("/save")
    public ResultListVO saveProduct(@RequestBody @Validated ProductForm productForm,
                                    BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new NullParameterException();
        }

        ProductInfo productInfo = ProductFormToProductInfo.convert(productForm);

        productInfoServer.saveProduct(productInfo);

        return new ResultListVO();
    }

    /** 修改 */
    @PostMapping("/change")
    public ResultListVO changeProduct(@RequestBody @Validated ProductWidForm productWidForm,
                                    BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new NullParameterException();
        }

        ProductInfo productInfo = ProductWidFormToProductInfo.convert(productWidForm);

        productInfoServer.changeProduct(productInfo);

        return new ResultListVO();
    }

    /** 删除 */
    @PostMapping("/delete")
    public ResultListVO deleteProduct(@RequestBody JSONObject jsonObject){
        Integer id = jsonObject.getInteger("id");

        productInfoServer.deleteProduct(id);

        return new ResultListVO();
    }


}
